#include "ScenePrecompiled.hxx"
#include "Scene.hxx"

#include "InternalSceneStaticImpl.hxx"
#include "InternalSceneImpl.hxx"

Eifersucht::uint16 Eifersucht::Scene::s_uRefcounter = 0ui16; // Indicates the number of instances created 
Eifersucht::Scene::StaticImplPtr Eifersucht::Scene::s_pImpl = nullptr;

void Eifersucht::Scene::InternalRestart()
{
	InternalRelease();

	if ( !m_pRoot )
	{
		m_pRoot = new RootChild();
		m_pRoot->m_pParentScene = this;
	}
}

void Eifersucht::Scene::InternalRelease()
{
	Safe_Delete(m_pRoot);
	Safe_Delete(m_pImpl);
	Safe_Delete(s_pImpl);
}

Eifersucht::Scene::Scene() : 
	m_pRoot(nullptr),
	m_pImpl(nullptr)
{
	PrintToDebugWindowOnly8("Eifersucht. Scene. Creating scene.");
	InternalRestart();
}

Eifersucht::Scene::~Scene()
{
	PrintToDebugWindowOnly8("Eifersucht. Scene. Destoying scene.");
	InternalRelease();
}

Eifersucht::SceneChildPtr Eifersucht::Scene::GetRootChild()
{
	return m_pRoot;
}

bool Eifersucht::Scene::ImportFbx( _In_z_ Eifersucht::String16 wszFile )
{
	PrintToDebugWindowOnly8( "Eifersucht. Scene. Allocating external resources..." );
	Safe_Delete(s_pImpl); s_pImpl = new _Internal_static_impl; 
	Safe_Delete(m_pImpl); m_pImpl = new _Internal_impl(this); 
	PrintToDebugWindowOnly8( "Eifersucht. Scene. External resources allocated." );

	PrintToDebugWindowOnly8( "Eifersucht. Scene. Importing Fbx file..." );
	String8 szFile( wszFile.begin(), wszFile.end() );
	PrintToDebugWindowOnly8( szFile.data() );

	if ( m_pImpl->_Import_from_file( szFile.data() ) )
	{
		PrintToDebugWindowOnly8( "Eifersucht. Scene. Importing scene..." );
		m_pImpl->_Assign_recursively();
		PrintToDebugWindowOnly8( "Eifersucht. Scene. Imported successfully." );

		PrintToDebugWindowOnly8( "Eifersucht. Scene. Releasing external resources..." );
		m_pRoot->ReleaseExternalResourcesRecursively();
		Safe_Delete(m_pImpl);
		Safe_Delete(s_pImpl);
		PrintToDebugWindowOnly8( "Eifersucht. Scene. External resources released." );

		return true;
	}

	PrintToDebugWindowOnly8( "Eifersucht. Scene. Failed to import scene." );
	PrintToDebugWindowOnly8( "Eifersucht. Scene. Releasing external resources..." );
	m_pRoot->ReleaseExternalResourcesRecursively();
	Safe_Delete(m_pImpl);
	Safe_Delete(s_pImpl);
	PrintToDebugWindowOnly8( "Eifersucht. Scene. External resources released." );

	return false;
}
